#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：FolderCleaner
@File ：FolderCleaner.py
@IDE  ：PyCharm
@Author ：李涵彬
@Date ：2025/2/24 下午7:12
"""

import time
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import shutil
import logging
import threading


class FolderCleanerApp(tk.Tk):
	def __init__(self):
		super().__init__()
		self.title("文件夹清理工具")
		self.geometry("700x400")  # 设置初始窗口大小
		self.resizable(True, True)  # 允许窗口大小调整
		self.thread_pool = None

		# 初始化界面
		self.init_ui()

	def init_ui(self):
		"""创建用户界面"""
		# 根目录选择
		root_dir_frame = tk.Frame(self)
		root_dir_frame.grid(row=0, column=0, padx=10, pady=10, sticky="ew")
		tk.Label(root_dir_frame, text="根目录：", width=10, anchor=tk.W).grid(row=0, column=0)
		self.root_dir_entry = tk.Entry(root_dir_frame, width=50)
		self.root_dir_entry.grid(row=0, column=1, padx=5, pady=5)
		tk.Button(root_dir_frame, text="选择目录", command=self.browse_root_dir, width=10) \
			.grid(row=0, column=2, padx=5, pady=5)

		# 目标文件夹选择
		target_folders_frame = tk.Frame(self)
		target_folders_frame.grid(row=1, column=0, padx=10, pady=10, sticky="ew")
		tk.Label(target_folders_frame, text="目标文件夹名称（多个用逗号分隔）：", width=35, anchor=tk.W) \
			.grid(row=0, column=0)
		self.target_folders_entry = tk.Entry(target_folders_frame, width=50)
		self.target_folders_entry.grid(row=0, column=1, padx=5, pady=5)

		# 执行按钮
		execute_frame = tk.Frame(self)
		execute_frame.grid(row=2, column=0, padx=10, pady=10, sticky="ew")
		self.execute_button = tk.Button(execute_frame, text="开始清理", command=self.execute_cleanup, width=20)
		self.execute_button.grid(row=0, column=0, padx=10, pady=10)

		# 清理结果展示
		result_frame = tk.Frame(self)
		result_frame.grid(row=3, column=0, padx=10, pady=10, sticky="ew")
		tk.Label(result_frame, text="清理进度：").grid(row=0, column=0, padx=5, pady=5, sticky="w")
		self.progress = ttk.Progressbar(result_frame, orient=tk.HORIZONTAL, length=300, mode='determinate')
		self.progress.grid(row=0, column=1, padx=5, pady=5, sticky="ew")

	def browse_root_dir(self):
		"""选择根目录"""
		selected_dir = filedialog.askdirectory()
		if selected_dir:
			self.root_dir_entry.delete(0, tk.END)
			self.root_dir_entry.insert(0, selected_dir)

	def execute_cleanup(self):
		"""执行清理操作"""
		# 获取输入
		root_dir = self.root_dir_entry.get()
		folder_names = [name.strip() for name in self.target_folders_entry.get().split(',')]

		# 输入验证
		if not root_dir:
			messagebox.showerror("输入错误", "请选择根目录！")
			return
		if not folder_names:
			messagebox.showerror("输入错误", "请输入目标文件夹名称！")
			return

		# 初始化日志
		logging.basicConfig(filename='clean_log.txt', level=logging.INFO,
							format='%(asctime)s - %(message)s')

		# 检查权限
		if not os.access(root_dir, os.W_OK):
			messagebox.showerror("权限错误", "您没有权限访问根目录！")
			return

		# 查找目标文件夹
		target_folders = []
		for root, dirs, _ in os.walk(root_dir):
			for dir_name in dirs:
				if dir_name in folder_names:
					target_folders.append(os.path.join(root, dir_name))

		if not target_folders:
			messagebox.showinfo("未找到目标", "没有找到需要清理的文件夹！")
			return

		# 确认清理操作
		confirm_msg = f"即将清理以下 {len(target_folders)} 个文件夹的内容：\n\n" + \
					  '\n'.join(target_folders[:5]) + (
						  f'\n...... 和其他 {len(target_folders) - 5} 个文件夹...' if len(target_folders) > 5 else '')
		confirmation = messagebox.askokcancel("确认操作", confirm_msg)
		if not confirmation:
			return

		# 开始清理
		total_folders = len(target_folders)
		self.progress['maximum'] = total_folders
		self.progress.start()

		# 多线程清理
		for folder in target_folders:
			threading.Thread(target=self._clean_folder, args=(folder,)).start()

		# 模拟进度条更新（实际应根据清洁进度动态更新）
		# 这里由于多线程操作，无法精确获取进度，可以考虑使用事件驱动或队列方式更新进度条
		# 临时方案：每隔一段时间更新进度条
		self.progress_update(total_folders)

		# 清理完成后提示
		self.progress.stop()
		messagebox.showinfo("清理完成", f"成功清理了 {total_folders} 个文件夹的内容！")

	def progress_update(self, total_folders):
		"""模拟进度条更新"""
		for i in range(total_folders):
			self.progress['value'] = i + 1
			self.update_idletasks()
			# time.sleep(0.1)  # 模拟清理操作的延迟

	def _clean_folder(self, folder_path):
		"""清理单个文件夹内容"""
		try:
			for item in os.listdir(folder_path):
				item_path = os.path.join(folder_path, item)
				if os.path.isfile(item_path):
					os.remove(item_path)
				elif os.path.isdir(item_path):
					shutil.rmtree(item_path)
				logging.info(f"已清理：{item_path}")
		except Exception as e:
			logging.error(f"清理失败：{folder_path} - {e}")


if __name__ == "__main__":
	app = FolderCleanerApp()
	app.mainloop()
